#!/bin/bash
function install_nexus() {
    echo -e "${blue}当前正在执行的操作为:${nocolor} ${green}安装Nexus${nocolor}"
    echo ""
    nexusHome="$workHome/packages/nexus"
    nexusoPid=`ps aux|grep nexus|grep java|grep -v grep|awk '{print $2}'`
    if [ -n "$nexusoPid" ];then
        echo -e "$Error 系统已经存在正在运行的Nexus请停止并卸载后继续！"
        anykeyback
        return 1
    fi
    echo -ne "${blue}请确认已安装JDK，Nexus与JDK对应关系如下${nocolor}
2.0-2.11.1：      Java 7
2.11.2-2.13.0:    建议Java8或Java 7u79+
2.14.0-2.14.10：  推荐Java 8，JAVA 7未测试
2.14.11+：        JAVA 8
更详细的版本要求，请参见使用帮助
继续[Yy,Enter],退出[Nn]: "
    read isYn
    [[ $isYn != [Nn] ]] || { sleep 0.5;return 1; }
    echo ""
    
    echo -ne "选择Nexus版本
${green}2.13.0${nocolor}     需要JAVA 7
${green}2.14.10${nocolor}    建议Java 8
${green}2.14.17${nocolor}    需要JAVA 8
${green}3.23.0${nocolor}     需要JAVA 8
${green}[Oo]ther${nocolor}   自定义版本
请输入要安装的版本[2.13.0]: "
    read nexusVer
    nexusVer=${nexusVer:-2.13.0}
    nexusVer=`echo $nexusVer`
    if [ "$nexusVer" == "Other" ] || [[ $nexusVer == [Oo] ]];then
        echo -ne "请输入要安装的Nexus版本: "
        read nexusVer
        nexusVer=${nexusVer:-2.13.0}
    fi
    nexusVer=`echo $nexusVer`
    nexusPack=`ls $nexusHome 2>/dev/null|grep "nexus-$nexusVer.*.tar.gz"|head -n1`
    if [ -z "$nexusPack" ];then
        echo -e "$Error packages/nexus目录未找到要安装的nexus版本！"
        anykeyback
        return 1
    fi
    echo ""
    
    echo -ne "请输入Nexus安装目录[/usr/local/nexus]: "
    read -e nexusPath
    nexusPath=${nexusPath:-/usr/local/nexus}
    nexusPath=`echo $nexusPath`
    nexusPath=${nexusPath%/}
    echo ""
    isNull=`ls $nexusPath/* 2>/dev/null | wc -l`
    if [[ $isNull -gt 0 ]];then
        echo -ne "安装目录非空，继续安装会删除已有数据！\n继续[Yy,Enter],退出[Nn]: "
        read isYn
        if [[ $isYn == [Nn] ]];then
          sleep 0.5
          return 1
        fi
        echo ""
    fi
    
    command -v ss >/dev/null 2>&1
    if [ "$?" == "0" ];then
        listen_cmd="ss -lnpt"
    else
        command -v netstat >/dev/null 2>&1
        if [ "$?" == "0" ];then
          listen_cmd="netstat -tnlp"
        fi
    fi
    [[ $listen_cmd ]] && PortCheck=Yes || PortCheck=No
    PortUsed=
    PortUsed_Pro=
    nexusPort=
    while [[ ! "$nexusPort" =~ ^[1-9][0-9]+$ || "$PortUsed" == "Yes" ]]
    do
        echo -ne "请输入Nexus监听端口[8081]: "
        read nexusPort
        nexusPort=${nexusPort:-8081}
        if [[ ! "$nexusPort" =~ ^[1-9][0-9]+$ ]];then
             echo -e "$Warn nexus端口只能为两位及以上且不以0开头的数字组成，请重新输入！"
             sleep 0.3
        else
            if [ "$PortCheck" == "Yes" ];then
                PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${nexusPort} "`
                if [ -n "$PortUsed_Pro" ];then
                  PortUsed=Yes
                  echo -e "$Warn nexus监听端口已被使用，请重新输入！"
                else
                  PortUsed=No
                fi
            else
                PortUsed=No
            fi
        fi
    done
    nexusPort=${nexusPort:-8081}
    nexusPort=`echo $nexusPort`
    echo ""
    
    echo -ne "请输入Nexus运行用户[root]: "
    read nexusUser
    nexusUser=${nexusUser:-root}
    nexusUser=`echo $nexusUser`
    echo ""

    source /etc/profile >/dev/null 2>&1
    source ~/.bash_profile >/dev/null 2>&1
    source ~/.bashrc >/dev/null 2>&1
    javaPath=`command -v java`
    if [ -z "$javaPath" ];then
        echo -ne "未找到到java命令，请输入java命令路径: "
        read -e javaPath
    else
        echo -ne "检测到java命令路径为$javaPath\n确认[Yy,Enter],修改[Mm]: "
        read isMm
        if [[ $isMm == [Mm] ]];then
          echo -ne "请输入java命令位置: "
          read -e javaPath
        fi
    fi
    javaPath=`echo $javaPath`
    javaOut=`$javaPath -version 2>&1|grep 'version "'`
    echo ""
    if [ -z "$javaOut" ];then
        echo -e "$Error java命令不存在或者不可执行，退出nexus安装！"
        anykeyback
        return 1
    fi
    
    # java版本信息
    java_version=$($javaPath -version 2>&1|head -n 1)
    
    echo -ne  "${blue}Nexus安装信息汇总${nocolor}
---------------------------------------------
Nexus版本：$nexusVer
Nexus路径：$nexusPath
Nexus端口：$nexusPort
Nexus运行用户：$nexusUser
JAVA命令：$javaPath
JDK版本信息：$java_version
---------------------------------------------
继续[Yy,Enter],退出[Nn]: "
    read isYn
    [[ $isYn != [Nn] ]] || { sleep 0.5;return 1; }
    echo ""
    
    echo ""
    echo -e "${cyan}将开始Nexus安装过程${nocolor}"
    echo ""
    
    nexus_MainVer=`echo $nexusVer|awk -F"." '{print $1}'`
    if [ "$nexus_MainVer" == "3" ];then
        reqUrl="http://$ipaddr:$nexusPort/"
        console_cmd="nexus run"
    else
        reqUrl="http://$ipaddr:$nexusPort/nexus/"
        console_cmd="nexus console"
    fi
    nexusUPw=`strings /dev/urandom |grep -o '[[:alnum:]_%@!]'|head -n 25|tr -d '\n'`
    
    cd $nexusHome

    echo -e "$Info ${purple}创建Nexus运行用户${nocolor}"
    isExistU=`cat /etc/passwd|grep "^$nexusUser:"`
    if [ -z "$isExistU" ];then
        /usr/sbin/useradd $nexusUser
        echo "$nexusUPw"|passwd --stdin $nexusUser
    else
        if [ "$nexusUser" != "root" ];then
         /usr/sbin/usermod -s /bin/bash $nexusUser
         echo "$nexusUPw"|passwd --stdin $nexusUser
        fi
    fi
    
    echo -e "$Info ${purple}开始安装Nexus${nocolor}"
    rm -rf $nexusPath
    mkdir -p $nexusPath
    echo -e "$Info ${purple}解压Nexus安装包${nocolor}"
    tar zxf $nexusPack -C $nexusPath
    if [ "$?" != "0" ];then
        echo -e "$Error Nexus安装包损坏，解压失败！退出安装"
        anykeyback
        return 1
    fi
        
    echo -e "$Info ${purple}修改Nexus配置${nocolor}"
    nexusBinPath="$nexusPath/`ls $nexusPath|grep nexus-$nexusVer`"
    real_javaPath=$(readlink -f $javaPath)
    javaHome=${real_javaPath%%/bin/*}
    
    if [ "$nexus_MainVer" == "3" ];then
        sed -i "s/^[# ]*run_as_user=.*/run_as_user=$nexusUser/g" $nexusBinPath/bin/nexus
        sed -i "/# INSTALL4J_JAVA_HOME_OVERRIDE=/a INSTALL4J_JAVA_HOME_OVERRIDE=$javaHome" $nexusBinPath/bin/nexus
        sed -i "s/^application-port=.*/application-port=$nexusPort/g" $nexusBinPath/etc/nexus-default.properties
    else
        sed -i "s/^[# ]*RUN_AS_USER=.*/RUN_AS_USER=$nexusUser/g" $nexusBinPath/bin/nexus
        sed -i "s#^wrapper.java.command=.*#wrapper.java.command=$javaPath#g" $nexusBinPath/bin/jsw/conf/wrapper.conf
        sed -i "s/^application-port=.*/application-port=$nexusPort/g" $nexusBinPath/conf/nexus.properties
    fi
    chown -R $nexusUser:$nexusUser $nexusPath
    echo -e "$Info ${purple}添加nexus服务脚本，并设置开机启动${nocolor}"
    systemctl disable nexus >/dev/null 2>&1
    /sbin/chkconfig --level 2345 nexus off >/dev/null 2>&1
    rm -rf /etc/init.d/nexus >/dev/null 2>&1
    rm -rf /etc/systemd/system/nexus.service >/dev/null 2>&1
    systemctl --version >/dev/null 2>&1
    if [ "$?" != "0" ];then
        cat >/etc/init.d/nexus<<EOF
#chkconfig:2345 20 90
#description:nexus
#processname:nexus
EXEC=$nexusBinPath/bin/nexus
case \$1 in
start) 
    \$EXEC start
    ;;
stop)
    \$EXEC stop
    ;;
status)
    \$EXEC status
    ;;
restart)
    \$EXEC restart
    ;;
dump)
    \$EXEC dump
    ;;
console)
    \$EXEC console
    ;;
*)
   echo "Usage: nexus console|start|stop|restart|status|dump"
   ;;
esac
EOF
        chmod +x /etc/init.d/nexus
        /sbin/chkconfig --add nexus
        /sbin/chkconfig nexus on
    else
        cat >/etc/systemd/system/nexus.service<<EOF
[Unit]
Description=nexus service
After=network.target
  
[Service]
Type=forking
LimitNOFILE=65536
ExecStart=$nexusBinPath/bin/nexus start
ExecStop=$nexusBinPath/bin/nexus stop
User=$nexusUser
Restart=on-abort
TimeoutSec=600
  
[Install]
WantedBy=multi-user.target
EOF
        systemctl daemon-reload
        systemctl enable nexus >/dev/null 2>&1
    fi

    echo -e "$Info ${purple}启动Nexus${nocolor}"
    systemctl start nexus || service nexus start
    echo -e "$Info ${purple}等待Nexus启动中.....${nocolor}"
    n=1
    curl --fail $reqUrl >/dev/null 2>&1
    exitstatus="$?"
    while [ "$exitstatus" != "0" ]
    do
      printf "%s %-3s %s\r" "等待nexus启动" "$n/65" "s"
      let n+=1
      sleep 1
      curl --fail $reqUrl >/dev/null 2>&1
      exitstatus="$?"
      if [ $n -gt 20 ];then
         nexusRPid=`ps aux|grep nexus|grep java|grep -v grep|awk '{print $2}'`
         if [ -z "$nexusRPid" ];then
             break
         fi
      fi
      if [ $n -gt 65 ];then
         break
      fi
    done
    echo ""

    #判断是否启动
    echo ""
    sleep 0.30
    UserUID=`cat /etc/passwd|grep "^$nexusUser:"|awk -F":" '{print $3}'`
    pass_info=
    if [ -n "$UserUID" -a "$nexusUser" != "root" ];then
        pass_info="$nexusUser用户密码为：$nexusUPw，请牢记或修改！"
    fi
    #nexus3.17后默认admin密码为随机
    passwdFile=`find $nexusPath/sonatype-work/ -name "admin.password" -type f`
    [[ $passwdFile ]] && adminPw=`cat $passwdFile` || adminPw="admin123"
    nexusUPid=`ps aux -u $UserUID|grep nexus|grep java|grep -v grep|awk '{print $2}'`
    nexusPid=`ps aux|grep nexus|grep java|grep -v grep|awk '{print $2}'`
    if [ -n "$nexusPid" ];then
        if [ -n "$nexusUPid" ];then
          echo -e "$Info ${light_green}Nexus安装成功${nocolor}
--------------------------------
访问地址：$reqUrl
默认管理用户密码为：admin/$adminPw
$pass_info
-------------------------------
"
        else
          echo -e "$Warn Nexus程序未按指定用户运行，请检查配置文件！"
        fi
    else
        echo -e "$Error Nexus安装失败！！！\n请使用$console_cmd模式启动以排查错误"
    fi
    anykeyback
}
